package com.mojo.nio.channel;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * FileChannel示例
 * <p>channel相对于流来时是无方向的，换言之，它是双向的。FileChannel可以从文件中读写数据
 * 通道和缓冲区基本用法
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/11/14 15:38
 */
public class FileChannelDemo {
    public static void main(String[] args) throws IOException {
        channel();
        //fileInputSteam();
    }

    //NIO包使用管道实现文件拷贝

    private static void channel() {
        long start = System.currentTimeMillis();
        File inFile = new File("e:\\我滴图片.zip");
        FileChannel inFc;
        FileChannel outFc;
        try (FileInputStream inputStream = new FileInputStream(inFile);
             FileOutputStream outputStream = new FileOutputStream("e:\\图片.zip")) {
            // 管道
            inFc = inputStream.getChannel();
            outFc = outputStream.getChannel();
            ByteBuffer buffer = ByteBuffer.allocateDirect(8092 * 8);
            while (true) {
                int read = inFc.read(buffer);
                if (read <= 0) {
                    break;
                }
                // 切换读写
                buffer.flip();
                // 写缓冲区
                outFc.write(buffer);
                buffer.clear();
            }
            long end = System.currentTimeMillis();
            System.out.println(">>>>" + (end - start) + "毫秒");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void fileInputSteam() throws FileNotFoundException {
        long start = System.currentTimeMillis();
        File inFile = new File("e:\\我滴图片.zip");
        try (FileInputStream inputStream = new FileInputStream(inFile);
             FileOutputStream outputStream = new FileOutputStream("e:\\图片.zip");) {
            BufferedInputStream bufferedInput = new BufferedInputStream(inputStream);
            BufferedOutputStream bufferedOut = new BufferedOutputStream(outputStream);
            int read;
            byte[] bytes = new byte[8092 * 8];
            while ((read = bufferedInput.read(bytes)) > -1) {
                bufferedOut.write(bytes, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println(">>>>" + (end - start) + "毫秒");
    }
}
